package com.gopay.common.util;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import org.apache.xerces.impl.dv.util.Base64;

import java.util.Random;


/**  
 * 字符串加、解密
 * @author LiLiLi
 * @KeyUtil.java
 */  
public class KeyUtil {   
  
	    public static String encryptDES(String encryptString, String encryptKey) throws Exception {  
	        SecretKeySpec key = new SecretKeySpec(encryptKey.getBytes(), "DES");  
	        Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");  
	        cipher.init(Cipher.ENCRYPT_MODE, key);  
	        byte[] encryptedData = cipher.doFinal(encryptString.getBytes());  
	       
	        return Base64.encode(encryptedData);  
	    }  
	    public static String decryptDES(String decryptString, String decryptKey) throws Exception {  
	        byte[] byteMi = new Base64().decode(decryptString);  
	        SecretKeySpec key = new SecretKeySpec(decryptKey.getBytes(), "DES");  
	        Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");  
	        cipher.init(Cipher.DECRYPT_MODE, key);  
	        byte decryptedData[] = cipher.doFinal(byteMi);  
	        return new String(decryptedData);  
	    }

    
    /**
     * 获得随机key,length 为长度
     * @param length
     * @return
     */
    public static String getRandKey(int length)
    {
        String keyStr = "";
        Random random = new Random();
        char chars[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g','0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
        for(int i=0;i<length;i++){
            keyStr +=chars[random.nextInt(chars.length)];
        }
        System.out.println("getRandKey keyStr:==="+keyStr);
        return keyStr;
    }
	    
	    public static void main(String[] args) throws Exception {  
	    	
	    }  
}  
